#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''文章增删改查'''

from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
import json
import os
from repository import models
from utils.pagination import Page
from forms import backend_forms
from utils.xss import XSSFilter
from django.db import transaction
from ..auth.auth import check_login

@check_login
def article(request, **kwargs):
    """
    博主个人文章管理
    """
    blog_nid = request.session.get('blog_nid')
    condition = {'blog_id': blog_nid}
    if kwargs:
        for k,v in kwargs.items():
            if v:
                kwargs[k] = int(v)
            else:
                kwargs[k] = 0
                continue
            if v == '0':
                continue
            else:
                condition[k] = v

    category_list = models.Category.objects.filter(blog_id=blog_nid).all()
    type_list = models.Article.type_choices
    blog_nid = request.session.get('blog_nid')
    p = request.GET.get('p')
    current_page = int(p if p else 1)  # 获取当前页
    per_page_count = 3  # 每页显示3条数据

    if blog_nid:
        data_count = models.Article.objects.filter(blog_id=blog_nid).count()
    else:
        data_count = 0
    my_page = Page(
        current_page=current_page,
        data_count=data_count,
        per_page_count=per_page_count,
        pager_num=5,
    )
    if blog_nid:
        query_res = models.Article.objects.filter(**condition)[my_page.start:my_page.end].values('nid','title')
    else:
        query_res = []
    page_str = my_page.page_str('/backend/article.html')

    res_dict = {
        'category_list': category_list,
        'type_list': type_list,
        'article_list': query_res,
        'page_str': page_str,
        'args': kwargs,
        'data_count': data_count
    }
    return render(request, 'backend_article.html', res_dict)


@check_login
def add_article(request):
    """
    添加文章
    """
    blog_id = request.session.get('blog_nid')
    if request.method == "GET":
        form_obj = backend_forms.EditArticleForm(blog_id)
        return render(request, 'backend_add_article.html', {'form_obj': form_obj})

    elif request.method == "POST":
        form_obj = backend_forms.EditArticleForm(blog_id,request.POST)
        if form_obj.is_valid():
            with transaction.atomic():
                article_obj = models.Article.objects.create(
                    title=form_obj.cleaned_data['title'],
                    summary=form_obj.cleaned_data['summary'],
                    blog_id=blog_id,
                    category_id= form_obj.cleaned_data['category'],
                    article_type= form_obj.cleaned_data['article_type'],
                )
                for tag_id in form_obj.cleaned_data['tag']:
                    models.Article2Tag.objects.create(article_id=article_obj.nid,tag_id=tag_id)
                content = XSSFilter().process(form_obj.cleaned_data['content'])
                models.ArticleDetail.objects.create(content=content,article_id=article_obj.nid)

            return redirect('/backend/article.html')
        else:
            return render(request, 'backend_add_article.html', {'form_obj': form_obj})


@check_login
def edit_article(request, nid):
    """
    编辑文章
    """
    blog_id = request.session.get('blog_nid')
    article_obj = models.Article.objects.filter(nid=nid).prefetch_related('articledetail','tags').only('title','summary','articledetail','category_id','article_type','tags').first()

    if request.method == "GET":
        choiced_tags = []
        for row in article_obj.tags.values_list('nid'):
            choiced_tags.append(row[0])

        inital_data = {
            'title': article_obj.title,
            'summary': article_obj.summary,
            'content': article_obj.articledetail.content,
            'article_type': article_obj.article_type,
            'category': article_obj.category_id,
            'tag': choiced_tags
        }
        form_obj = backend_forms.EditArticleForm(blog_id, initial=inital_data)
        return render(request, 'backend_edit_article.html',{'form_obj': form_obj,'nid':nid})

    elif request.method == "POST":
        form_obj = backend_forms.EditArticleForm(blog_id, request.POST)
        if form_obj.is_valid():
            with transaction.atomic():
                article_obj.title = form_obj.cleaned_data['title']
                article_obj.summary = form_obj.cleaned_data['summary']
                article_obj.blog_id = blog_id
                article_obj.category_id = form_obj.cleaned_data['category']
                article_obj.article_type = form_obj.cleaned_data['article_type']
                article_obj.tags.clear()
                article_obj.save()
                for tag_id in form_obj.cleaned_data['tag']:
                    models.Article2Tag.objects.create(article_id=article_obj.nid,tag_id=tag_id)
                content = XSSFilter().process(form_obj.cleaned_data['content'])
                models.ArticleDetail.objects.filter(article_id=nid).update(content=content)
            return redirect('/backend/article.html')
        else:
            return render(request, 'backend_edit_article.html', {'form_obj': form_obj})


@check_login
def del_article(request):
    """删除文章"""
    if request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}

        models.Article.objects.filter(nid=request.POST.get('nid')).delete()
        return HttpResponse(json.dumps(res_dict))


@check_login
def upload_file(request):
    """上传文件"""
    res_dict = {
        'error': 0,
        'url': None,
        'message': None,
    }
    if not request.session.get('blog_nid'):
        res_dict['error'] = 1
        res_dict['message'] = '上传失败'
    else:
        site = models.Blog.objects.filter(nid=request.session.get('blog_nid')).values_list('site').first()[0]
        print(site)
        file_obj = request.FILES.get('imgFile')
        dir_path = os.path.join('static', 'upload', site)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        file_path = os.path.join(dir_path, file_obj.name)
        file = open(file_path, 'wb')
        for item in file_obj.chunks():
            file.write(item)
        file.close()
        url = '/static/upload/%s/%s'%(site,file_obj.name)
        res_dict['url'] = url


    return HttpResponse(json.dumps(res_dict))